import json
import math
import os
import sys

import click
from PIL import Image


@click.group()
def image():
    """图片工具"""
    pass


@image.command()
@click.option('-f', '--file', type=click.Path(exists=True), required=True, help='图片源文件')
@click.option('-s', '--size', type=click.Choice(['256', '512']), default='512', show_default=True, help='切图大小')
@click.option('-o', '--out', help='切图输出目录')
@click.option('--origin', type=click.Choice(['top', 'bottom']), default='bottom', show_default=True, help='原点(top 左上角 | bottom 左下角)')
def clip(file: str, size: int, out: str, origin: str):
    """切图"""
    ext = get_file_ext(file)
    out = get_out_path(file, out)

    img = Image.open(file)
    size = int(size)

    width, height = img.size
    rows = math.ceil(width / size)
    cols = math.ceil(height / size)

    for col in range(cols):
        for row in range(rows):
            region, col_idx = clip_get_region(img.size[1], size, cols, row, col, origin)
            img_copy = img.crop(region)
            idx = f'{col_idx}_{row}'
            img_copy.save(f'{out}/{idx}{ext}', img.format)
            img_copy.close()

    img.close()

    file_slices = f'{out}/slices.json'
    with open(file_slices, 'w') as fd:
        json.dump({'file': os.path.basename(file), 'width': width, 'height': height, 'size': size, 'rows': rows, 'cols': cols}, fd)


@image.command()
@click.option('-f', '--file', type=click.Path(exists=True), required=True, help='图片源文件')
@click.option('-s', '--size', type=click.Choice(['256', '512']), default='256', show_default=True, help='缩略图大小')
@click.option('-o', '--out', help='缩略图输出目录')
def thumb(file: str, size: int, out: str):
    """缩略图"""
    ext = get_file_ext(file)
    out = get_out_path(file, out)
    size = int(size)

    img = Image.open(file)
    width, height = img.size

    new_width, new_height = size, size
    if width > height:
        new_height = math.ceil(height / (width / new_width))
    else:
        new_width = math.ceil(width / (height / new_height))

    img_new = img.resize((new_width, new_height))
    img_new.save(f'{out}/min{ext}')


def get_file_ext(file: str) -> str:
    ext = os.path.splitext(file)[1]
    if ext not in ['.png', '.jpeg', '.jpg']:
        print(f'image file: {file} 不是图片文件')
        sys.exit(1)

    return ext


def get_out_path(file: str, out: str) -> str:
    if out is not None:
        if not os.path.exists(out):
            os.makedirs(out)
        return out

    out = os.path.splitext(file)[0]
    if not os.path.exists(out):
        os.makedirs(out)

    return out


def clip_get_region(height, size: int, cols: int, row: int, col: int, origin: str) -> ((int, int, int, int), int):
    pos_x = row * size

    if origin == 'top':
        pos_y = col * size
        return (pos_x, pos_y, pos_x + size, pos_y + size), col

    pos_y = height - (cols - (col + 1)) * size
    return (pos_x, pos_y - size, pos_x + size, pos_y), cols - (col + 1)
